﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Visio = Microsoft.Office.Interop.Visio;
using System.Globalization;

namespace SPNetworkTopology
{
    class CreateRecordset
    {
        /// <summary>
        /// SharePoint site url
        /// </summary>
        private string SPSiteURL;
        /// <summary>
        /// SharePoint List GUID
        /// </summary>
        private string SPListDataGUID;
        /// <summary>
        /// SharePoint List name
        /// </summary>
        private string SPListName;
        /// <summary>
        /// List of filterd columns
        /// </summary>
        private List<string> SelectedColumns;

        public CreateRecordset(DataLinking dataLinkingObject)
        {
            //Load the SharePoint information
            this.SPListDataGUID = dataLinkingObject.SPListGUID;
            this.SelectedColumns = dataLinkingObject.SelectedColumns;
            this.SPListName = dataLinkingObject.SPListName;
            this.SPSiteURL = dataLinkingObject.SPSiteName;

            //Create the recorset
            this.CreateDataRecordSet();
        }        

        private void CreateDataRecordSet()
        {
            Visio.Document currentDocument = VisioObjects.visApplication.ActiveDocument;
            string connectionString = String.Format("PROVIDER=WSS;DATABASE={0};LIST={1};",this.SPSiteURL,String.Concat("{",this.SPListDataGUID,"}"));
            this.SelectedColumns = this.SelectedColumns.Select(val => String.Concat("[", val, "]")).ToList();
            string commandString = String.Concat("SELECT ", String.Join(",", this.SelectedColumns.ToArray()), " FROM [", this.SPListName, "] ;"); 
            Visio.DataRecordset spTopologyRecordset = currentDocument.DataRecordsets.Add(connectionString, commandString, 0, "SharePoint Farm Info");
           
            //Show the external data window
            VisioObjects.visApplication.ActiveWindow.Windows.get_ItemFromID(Convert.ToInt16(Visio.VisWinTypes.visWinIDExternalData, CultureInfo.InvariantCulture)).Visible = true;
        }
    }
}
